<template>
  <div class="table-container">
    <!--按钮行-->
    <div class="btn-row">
      <div class="left">
        <el-button type="primary" class="primary-btn" icon="el-Plus" @click="addDetail">
          新建
        </el-button>
        <el-button type="default" class="default-btn">批量导入</el-button>
      </div>
      <el-button type="primary" class="primary-btn" icon="el-Download" @click="$emit('download')">下载
      </el-button>
    </div>

    <el-table
      :data="data"
      class="table"
      stripe
      :default-sort="{ prop: 'date', order: 'descending' }"
      table-layout="auto"
    >
      <el-table-column
        type="index"
        label="编号"
        :index="indexMethod"
        min-width="80"
        align="center"
      />
      <el-table-column prop="id" v-if="false"/>
      <el-table-column
        prop="familyId"
        label="所属家庭"
        min-width="100"
      >
        <template #default="scope">
          <div class="family-cell">
            <el-icon>
              <el-House/>
            </el-icon>
            <span>{{ scope.row.familyName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="content"
        label="收支内容"
        min-width="120"
        show-overflow-tooltip
      />
      <el-table-column
        prop="tagId"
        label="标签"
        min-width="100"
      >
        <template #default="scope">
          <div class="tag-container">
            <el-tag
              class="tag-item"
              size="small"
            >
              {{ scope.row.tagName }}
            </el-tag>
          </div>

        </template>
      </el-table-column>
      <el-table-column
        prop="amount"
        label="金额"
        min-width="120"
        align="center"
      />
      <el-table-column
        prop="sourceType"
        label="来源类型"
        min-width="120"
      >
        <template #default="scope">
          <div class="type-cell"
               :style="{backgroundColor: getSourceTypeByCode(scope.row.sourceType).bgColor,
                        color: getSourceTypeByCode(scope.row.sourceType).color}">{{
              getSourceTypeByCode(scope.row.sourceType).desc
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="incomeExpenseType"
        label="收支类型"
        min-width="120"
      >
        <template #default="scope">
          <div class="type-cell"
               :style="{backgroundColor: getInExTypeByCode(scope.row.incomeExpenseType).bgColor,
                        color: getInExTypeByCode(scope.row.incomeExpenseType).color}">
            {{ getInExTypeByCode(scope.row.incomeExpenseType).desc }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="memberId"
        label="所属成员"
        min-width="100"
      >
        <template #default="scope">
          <div class="family-cell">
            <el-icon>
              <el-User/>
            </el-icon>
            <span>{{ scope.row.memberName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="备注"
        min-width="100"
      >
        <template #default="scope">
          <el-tooltip
            :content="scope.row.remark || '无备注'"
            placement="top"
            :disabled="!scope.row.remark || scope.row.remark.length <= 10"
          >
            <div class="remark-cell">
              {{
                scope.row.remark ? (scope.row.remark.length > 10 ? scope.row.remark.substring(0, 10) + '...' : scope.row.remark) : '无备注'
              }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column
        prop="date"
        label="业务日期"
        sortable
        min-width="100"
      />
      <el-table-column
        label="操作"
        min-width="180"
        fixed="right"
      >
        <template #default="scope">
          <div class="action-buttons">
            <el-button
              size="small"
              class="edit-btn"
              @click="handleEdit(scope.$index,scope.row)"
            >编辑
            </el-button>
            <el-button
              size="small"
              class="delete-btn"
              @click="handleDelete(scope.row)"
            >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="localCurrentPage"
        v-model:page-size="localPageSize"
        :pages="localPages"
        :page-sizes="[10,50,100, 200, 300, 400]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!--新建与编辑-->
  <EditDialog
    v-model:visible="editDialogVisible"
    :form-data="dialogFormData"
    :family-list="familyList"
    :tag-list="tagList"
    :income-expense-types="incomeExpenseTypes"
    :source-types="sourceTypes"
    @refresh="refresh"
  />

</template>

<script setup lang="ts">
import {computed, ref, watch} from 'vue';
import type {Detail, Dictionary, Family, Tag} from "@/api/detail/type.ts";
import {useDetailStore} from "@/stores/useDetailStore.ts";
import EditDialog from "@/views/detail/EditDialog.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {deleteDetail} from "@/api/detail"

const props = defineProps<{
  data: Detail[];
  currentFamilyId: number |null;
  familyList: Family[];
  tagList: Tag[];
  sourceTypes: Dictionary[];
  incomeExpenseTypes: Dictionary[];
  total: number;
  currentPage: number;
  pageSize: number;
  pages: number;
}>();

const currentFamilyId = computed(() => props.currentFamilyId);

const {getInExTypeByCode, getSourceTypeByCode} = useDetailStore();

const localCurrentPage = ref(props.currentPage);
const localPageSize = ref(props.pageSize);
const localPages = ref(props.pages);
watch(() => props.currentPage, (newVal) => {
  localCurrentPage.value = newVal;
});

watch(() => props.pageSize, (newVal) => {
  localPageSize.value = newVal;
});
watch(() => props.pages, (newVal) => {
  localPages.value = newVal;
});


// 编辑与新建dialog显示开关
const editDialogVisible = ref<boolean>(false);
//获取默认表单数据
const getDefaultFormData = (): Detail => ({
  id: null,
  familyId: currentFamilyId.value,
  familyName: null,
  content: null,
  amount: null,
  tagId: null,
  tagName: null,
  incomeExpenseType: 1,
  memberId: null,
  memberName: null,
  sourceType: null,
  date: null,
  remark: '',
});
const dialogFormData = ref<Detail>(getDefaultFormData());


// 编辑按钮点击
const handleEdit = (index: number, row: Detail) => {
  dialogFormData.value = {...row};
  editDialogVisible.value = true;
};


const emit = defineEmits(['size-change', 'current-change', 'refresh', 'download']);

//页面编号处理
const indexMethod = (index: number) => {
  return ++index;
};

//page_size改变触发
const handleSizeChange = (size: number) => {
  emit('size-change', size);
};

//current_page改变触发
const handleCurrentChange = (page: number) => {
  emit('current-change', page);
};

function refresh() {
  emit('refresh');
}


/**
 *  删除明细
 * @param row
 */
function handleDelete(row: Detail) {
  ElMessageBox.confirm(
    `确定要删除该明细吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      draggable: true,
      customClass: 'modern-message-box'
    }
  ).then(async () => {
    try {
      //删除明细
      const res = await deleteDetail(row.id!);
      if (res.code === "M000") {
        ElMessage.success("删除成功");
        //刷新
        refresh();
      }
    } catch (e) {
      console.error("删除明细失败", e)
      ElMessage.error("删除明细失败");
    }

  }).catch(() => {
  });
}


/**
 * 添加明细
 */
function addDetail() {
  editDialogVisible.value = true
  dialogFormData.value = getDefaultFormData();
}


</script>

<style scoped lang="scss">
.table-container {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
  min-height: 200px;
  overflow: hidden;
  box-sizing: border-box;
  background-color: $base-card-bg-color;
  border: 1px solid var(--el-border-color-light);
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);


  /* 按钮行 */
  .btn-row {
    width: 100%;
    flex-shrink: 0;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin-bottom: 20px;

    .left {
      display: flex;
      gap: 12px;
    }

    .primary-btn {
      background-color: #3370ff;
      color: white;
      border: none;
      font-size: 14px;
      height: 36px;
      padding: 0 16px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        background-color: #2a5fd8;
        box-shadow: 0 2px 8px rgba(51, 112, 255, 0.3);
      }
    }

    .default-btn {
      background-color: white;
      color: #606266;
      border: 1px solid #dcdfe6;
      font-size: 14px;
      height: 36px;
      padding: 0 16px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        color: #3370ff;
        border-color: #c6e2ff;
        background-color: #ecf5ff;
      }
    }
  }

  /* 表格样式 */
  .table {
    flex: 1;
    border-radius: 8px;
    border: 1px solid var(--el-border-color-light);

    /* 表头样式 */
    :deep(.el-table__header) {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 600;
        height: 48px;
        border-bottom: 1px solid var(--el-border-color-light);
      }
    }

    /* 单元格样式 */
    :deep(.cell) {
      color: #606266;
      padding: 11.3px 0;
      line-height: 1.5;
      font-size: 14px;
    }


    /* 悬停效果 */
    :deep(.el-table__body tr:hover>td) {
      background-color: #e9f7fb !important;
    }

    /* 行边框 */
    :deep(.el-table__row td) {
      border-bottom: 1px solid var(--el-border-color-lighter);
    }
  }

  /* 自定义单元格样式 */
  .family-cell {
    display: flex;
    align-items: center;
    gap: 8px;
    color: #1140f4;

    .el-icon {
      font-size: 16px;
    }
  }

  .remark-cell {
    color: #0aa8a8;
  }

  .tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    align-items: center;
  }

  .tag-item {
    background-color: #ecf5ff;
    color: #3370ff;
    border: 1px solid #d9ecff;
    border-radius: 4px;
  }

  .more-tag {
    background-color: #f0f2f5;
    color: #909399;
    border: none;
  }

  .tooltip-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    max-width: 200px;
  }

  .tooltip-tag {
    background-color: #f0f9eb;
    color: #67c23a;
    border: 1px solid #e1f3d8;
  }

  .empty-text {
    color: #c0c4cc;
  }

  .type-cell {
    padding: 4px 8px;
    border-radius: 4px;

    display: inline-block;

    &.expense {
      background-color: #fef0f0;
      color: #f56c6c;
      border: 1px solid #fde2e2;
    }

    &.income {
      background-color: #f0f9eb;
      color: #67c23a;
      border: 1px solid #e1f3d8;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;

    .edit-btn {
      background-color: #3370ff;
      color: white;
      border: none;

      &:hover {
        background-color: #2a5fd8;
      }
    }

    .delete-btn {
      background-color: #fef0f0;
      color: #f56c6c;
      border: 1px solid #fde2e2;

      &:hover {
        background-color: #f56c6c;
        color: white;
      }
    }
  }

  /* 分页样式 */
  .pagination-wrapper {
    flex-shrink: 0;
    padding: 16px 0;
    margin-top: 16px;
    display: flex;
    justify-content: center;
    border-top: 1px solid var(--el-border-color-light);

    :deep(.el-pagination) {
      .btn-prev, .btn-next, .el-pager li {
        border-radius: 4px;
        margin: 0 4px;
      }

      .el-pager li:not(.is-disabled).is-active {
        background-color: #3370ff;
      }
    }
  }
}
</style>
